package cqrtplm.service.impl;

import com.hustcad.plm.pdm.file.model.dto.BatchUploadDTO;
import com.hustcad.plm.pdm.file.service.TyplmFileHandleService;
import com.hustcad.plm.pdm.filevault.model.vo.FileDataVO;
import com.hustcad.plm.pdm.iteration.dto.TyplmCommonHistoryDTO;
import com.hustcad.plm.pdm.iteration.service.TyCommonHistoryService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.vo.AttributeVO;
import cqrtplm.service.RTProductPDFService;
import cqrtplm.util.ConvertExcelToPdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RTProductPDFServiceImpl implements RTProductPDFService {

    @Resource
    private TyCommonHistoryService tyCommonHistoryService;

    @Resource
    private TyplmFileHandleService fileHandleService;

    @Value("${file.upload.temp.dir}")
    private String fileExportDefaultDir;


    @Override
    public void productPDF(BigInteger workFlowContainerId) {

        List<Map<String,String>> dataList = new ArrayList<>();

        //todo 需要获取变更中 文档对象
        IdentifierEntity identifierEntity = new IdentifierEntity();

        //查询文档附件，删除 之前生成的历史记录。
        List<FileDataVO> fileListByEntity = this.fileHandleService.getFileListByEntity(identifierEntity);
        for(FileDataVO fileDataVO : fileListByEntity){
            String fileName = fileDataVO.getFileName();
            if("历史记录.pdf".equals(fileName)){
                List<BigInteger> fileIdList = new ArrayList<>();
                List<FileDataVO> fileDataVOList = fileDataVO.getFileDataVOList();
                for(FileDataVO fileDataVO1 : fileDataVOList){
                    fileIdList.add(new BigInteger(fileDataVO1.getFileID()));
                }
                fileIdList.add(new BigInteger(fileDataVO.getFileID()));
                this.fileHandleService.deleteFileByFileIdList(fileIdList);
            }
        }
        //查询文档对象的历史记录
        List<TyplmCommonHistoryDTO> versionHistory = tyCommonHistoryService.getVersionHistory(identifierEntity);
        for(TyplmCommonHistoryDTO typlmCommonHistoryDTO : versionHistory) {
            Map<String,String> map = new HashMap<>();
            map.put("version",typlmCommonHistoryDTO.getDisplayVersion());
            List<AttributeVO> ibaAttrs = typlmCommonHistoryDTO.getIbaAttrs();
            for(AttributeVO attributeVO : ibaAttrs){
                String attributeName = attributeVO.getAttributeEnName();
                if("changeDescription".equals(attributeName)){
                    map.put("changeDescription",attributeVO.getAttributeValue());
                }
                if("changeDocumentNumber".equals(attributeName)){
                    map.put("changeDocumentNumber",attributeVO.getAttributeValue());
                }
            }
            map.put("updatorDisplayName",typlmCommonHistoryDTO.getUpdatorDisplayName());
            map.put("modifystamp",typlmCommonHistoryDTO.getModifystamp().toString());
            dataList.add(map);
        }
        //获取当前登录用户
        UserDO user = TyAccountContext.getUser();
        String excelFilePath = fileExportDefaultDir + "历史记录.xlsx";
        String pdfFilePath = fileExportDefaultDir + "历史记录.pdf";
        exportToExcel(dataList,excelFilePath);
        new ConvertExcelToPdfUtil(excelFilePath,pdfFilePath);
        File pdfFile = new File(pdfFilePath);
        BatchUploadDTO batchUploadDTO = new BatchUploadDTO();
        List<MultipartFile> fileList = new ArrayList<>();
        try {
            FileInputStream input = new FileInputStream(pdfFile);
            MultipartFile multipartFile = new MockMultipartFile(
                    "file",
                    pdfFile.getName(),
                    "application/pdf",
                    input
            );
            fileList.add(multipartFile);
        } catch (Exception e){
            throw new RuntimeException();
        }
        batchUploadDTO.setFileList(fileList);
        batchUploadDTO.setUpdatoroid(user.getOid());
        batchUploadDTO.setUpdatorotype(TableTypeConstrant.TY_USER_OTYPE);
        batchUploadDTO.setOid(identifierEntity.getOid().toString());
        batchUploadDTO.setOtype(identifierEntity.getOtype());
        List<String> descriptionList = new ArrayList<>();
        descriptionList.add("历史记录");
        batchUploadDTO.setDescriptionList(descriptionList);
        this.fileHandleService.batchUploadFile(batchUploadDTO);
    }

    /**
     * 将数据导出到Excel文件
     * @param dataList 数据列表
     * @param fileName 文件名
     */
    private void exportToExcel(List<Map<String, String>> dataList, String fileName) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("sheet");
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"历史版本", "变更描述", "变更单据号", "修改这", "修改时间"};
            String[] keys = {"version", "changeDescription", "changeDocumentNumber", "updatorDisplayName", "modifystamp"};

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            // 填充数据
            int rowNum = 1;
            for (Map<String, String> data : dataList) {
                Row row = sheet.createRow(rowNum++);
                for (int i = 0; i < keys.length; i++) {
                    Cell cell = row.createCell(i);
                    cell.setCellValue(data.getOrDefault(keys[i], ""));
                }
            }
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            // 保存文件或提供下载
            FileOutputStream fileOut = new FileOutputStream(fileName);
            workbook.write(fileOut);
            fileOut.close();
        } catch (IOException e) {
            log.error("导出Excel失败", e);
        }
    }






}
